import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom/server';
import { Provider } from 'react-redux';
import configureStore from '../store';
import App from '../views/app';
import serialize from 'serialize-javascript';

export default (req, res) => {
  const initialState = {
    counter: { count: 0 },
    users: { users: [] }
  };
  
  const { store } = configureStore(initialState);
  
  const content = renderToString(
    <Provider store={store}>
      <StaticRouter location={req.url}>
        <App />
      </StaticRouter>
    </Provider>
  );

  const html = `
    <!DOCTYPE html>
    <html>
      <head>
        <title>SSR React App</title>
        <script>
          window.__INITIAL_STATE__ = ${serialize(store.getState())}
        </script>
      </head>
      <body>
        <div id="root">${content}</div>
        <script src="/bundle.js"></script>
      </body>
    </html>
  `;

  res.setHeader('Content-Type', 'text/html');
  res.send(html);
};
